//---------------------------------------------------------------------------

#include "vcl_stl.h"
#pragma hdrstop

#include "h_base.h"
#include "h_xml.h"
#include "h_global.h"
using namespace h_base;
using namespace h_xml;

#include "h_g.h"
#include "h_stage.h"
#include "h_server.h"

#include "t_mainform.h"
#include "h_i18n.h"
#include "h_portal.h"

#include "t_batlistform.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TBatListForm *BatListForm;
//---------------------------------------------------------------------------
__fastcall TBatListForm::TBatListForm(TComponent* Owner)
   : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TBatListForm::CheckBoxAllClick(TObject *Sender)
{
   if ( CheckBoxAll->Checked )
   {
      CheckBoxWaiting->Enabled = false;
      CheckBoxRunning->Enabled = false;
      CheckBoxPaused->Enabled = false;
      CheckBoxFail->Enabled = false;
      CheckBoxSuccess->Enabled = false;
      CheckBoxUnknown->Enabled = false;
   }
   else
   {
      CheckBoxWaiting->Enabled = true;
      CheckBoxRunning->Enabled = true;
      CheckBoxPaused->Enabled = true;
      CheckBoxFail->Enabled = true;
      CheckBoxSuccess->Enabled = true;
      CheckBoxUnknown->Enabled = true;
   }
}
//---------------------------------------------------------------------------

void __fastcall TBatListForm::Clear()
{
   BatMap.clear();
   BatList.clear();
   StringGrid1->RowCount = 2;
   StringGrid1->Rows[0]->Strings[0] = UTF8String(h_g::I18nString("t_batlistform:NO."));
   StringGrid1->Rows[0]->Strings[1] = UTF8String(h_g::I18nString("t_batlistform:NAME"));
   StringGrid1->Rows[0]->Strings[2] = UTF8String(h_g::I18nString("t_batlistform:DESCRIPTION"));
   StringGrid1->Rows[0]->Strings[3] = UTF8String(h_g::I18nString("t_batlistform:STATUS"));
   StringGrid1->Rows[0]->Strings[4] = UTF8String(h_g::I18nString("t_batlistform:START_TIME"));
   StringGrid1->Rows[0]->Strings[5] = UTF8String(h_g::I18nString("t_batlistform:END_TIME"));
   StringGrid1->Rows[0]->Strings[6] = UTF8String(h_g::I18nString("t_batlistform:ELAPSED"));
   StringGrid1->Rows[0]->Strings[7] = UTF8String(h_g::I18nString("t_batlistform:BATCH_DATE"));
   StringGrid1->Rows[0]->Strings[8] = UTF8String(h_g::I18nString("t_batlistform:NEXT_SCHEDULE_DATE"));

   for ( int i = 0; i < 9; i++ )
   {
      StringGrid1->Rows[1]->Strings[i] = "";
   }
}

void __fastcall TBatListForm::Reload()
{
   BatMap.clear();
   MainForm->SaveToBatList(BatMap);
   AssignRows();
}

void __fastcall TBatListForm::AssignRows()
{
   map<int, HBatListInfo> NewBatList;

   Filter(NewBatList);

   bool AllFlag = NewBatList.size() != BatList.size();

   if ( NewBatList.empty() )
   {
      StringGrid1->RowCount = 2;
      for ( int i = 0; i < 9; i++ )
      {
         StringGrid1->Rows[1]->Strings[i] = "";
      }
   }
   else
   {
      StringGrid1->RowCount = NewBatList.size() + 1;
      int i;
      map<int, HBatListInfo>::iterator Iter;
      map<int, HBatListInfo>::iterator IterNew;
      for ( Iter = BatList.begin(), IterNew = NewBatList.begin(), i = 1;
            i <= NewBatList.size(); i++, IterNew++ )
      {
         const HBatListInfo &NewInfo = IterNew->second;
         if ( AllFlag )
         {
            AssignOneRow(i, NewInfo);
         }
         else
         {
            const HBatListInfo &Info = Iter->second;
            if ( Info.Status != NewInfo.Status ||
                 Info.StartTime != NewInfo.StartTime ||
                 Info.EndTime != NewInfo.EndTime ||
                 Info.BatchDate != NewInfo.BatchDate ||
                 Info.NextScheduleDate != NewInfo.NextScheduleDate )
            {
               AssignOneRow(i, NewInfo);
            }
            Iter++;
         }
      }
   }

   BatList = NewBatList;
   UpdateButtons(StringGrid1->Selection.Top);
}

void __fastcall TBatListForm::AssignOneRow(int RowIdx, const HBatListInfo &Info)
{
   StringGrid1->Rows[RowIdx]->Strings[0] = Info.Idx + 1;
   StringGrid1->Rows[RowIdx]->Strings[1] = Info.Name;
   StringGrid1->Rows[RowIdx]->Strings[2] = Info.Description;
   StringGrid1->Rows[RowIdx]->Strings[3] = Info.Status;
   StringGrid1->Rows[RowIdx]->Strings[4] = FormatDateTime(Info.StartTime);
   StringGrid1->Rows[RowIdx]->Strings[5] = FormatDateTime(Info.EndTime);
   StringGrid1->Rows[RowIdx]->Strings[6] = Info.ElapsedTime;
   StringGrid1->Rows[RowIdx]->Strings[7] = Info.BatchDate;
   StringGrid1->Rows[RowIdx]->Strings[8] = Info.NextScheduleDate;
}

void __fastcall TBatListForm::Filter(map<int, HBatListInfo> &NewBatList)
{
   UTF8String NameFilter = EditText->Text.Trim().UpperCase();
   UTF8String StartTime1Filter = GetDateTime(UTF8String(EditStartTime1->Text).c_str());
   UTF8String StartTime2Filter = GetDateTime(UTF8String(EditStartTime2->Text).c_str());
   UTF8String EndTime1Filter = GetDateTime(UTF8String(EditEndTime1->Text).c_str());
   UTF8String EndTime2Filter = GetDateTime(UTF8String(EditEndTime2->Text).c_str());
   UTF8String ElapsedTimeFilter;
   UTF8String BatchDateFilter = EditBatchDate->Text.Trim();

   if ( EditElapsedTime->Text.Trim() != "" )
   {
      int Seconds;
      vector<string> StrVec;
      char TmpStr[80 + 1];
      SplitString(UTF8String(EditElapsedTime->Text).c_str(), ':', StrVec);
      switch ( StrVec.size() )
      {
      case 0 :
         Seconds = 0;
         break;
      case 1 :
         Seconds = StrToInt(StrVec[0].c_str());
         break;
      case 2 :
         Seconds = StrToInt(StrVec[0].c_str()) * 60 +
            StrToInt(StrVec[1].c_str());
         break;
      default :
         Seconds = StrToInt(StrVec[0].c_str()) * 3600 +
            StrToInt(StrVec[1].c_str()) * 60 +
            StrToInt(StrVec[2].c_str());
         break;
      }
      snprintf(TmpStr, 80, "%02d:%02d:%02d", Seconds / 3600,
         Seconds % 3600 / 60, Seconds % 60);
      ElapsedTimeFilter = TmpStr;
   }

   NewBatList.clear();

   for ( map<int, HBatListInfo>::iterator Iter = BatMap.begin();
         Iter != BatMap.end(); Iter++ )
   {
      const HBatListInfo &Info = Iter->second;
      if ( NameFilter != "" && Info.Name.Pos(NameFilter) == 0 &&
           Info.Description.UpperCase().Pos(NameFilter) == 0 )
      {
         continue;
      }
      if ( !CheckBoxAll->Checked )
      {
         bool Ok = false;
         if ( CheckBoxWaiting->Checked && Info.Status == "WAITING" )
         {
            Ok = true;
         }
         if ( CheckBoxRunning->Checked && Info.Status == "RUNNING" )
         {
            Ok = true;
         }
         if ( CheckBoxSuccess->Checked && Info.Status == "SUCCESS" )
         {
            Ok = true;
         }
         if ( CheckBoxFail->Checked && Info.Status == "FAIL" )
         {
            Ok = true;
         }
         if ( CheckBoxPaused->Checked && Info.Status == "PAUSED" )
         {
            Ok = true;
         }
         if ( CheckBoxUnknown->Checked && Info.Status == "UNKNOWN" )
         {
            Ok = true;
         }
         if ( !Ok )
         {
            continue;
         }
      }
      if ( StartTime1Filter != "00000000000000" && Info.StartTime < StartTime1Filter )
      {
         continue;
      }
      if ( StartTime2Filter != "00000000000000" && Info.StartTime > StartTime2Filter )
      {
         continue;
      }
      if ( EndTime1Filter != "00000000000000" && Info.EndTime < EndTime1Filter )
      {
         continue;
      }
      if ( EndTime2Filter != "00000000000000" && Info.EndTime > EndTime2Filter )
      {
         continue;
      }
      if ( ElapsedTimeFilter != "" && Info.ElapsedTime < ElapsedTimeFilter )
      {
         continue;
      }
      if ( BatchDateFilter != "" )
      {
         if ( Info.Status == "RUNNING" || Info.Status == "PAUSED" ||
              Info.Status == "FAILED" )
         {
            if ( Info.BatchDate == BatchDateFilter )
            {
               continue;
            }
         }
         if ( Info.Status == "WAITING" || Info.Status == "SUCCESS" )
         {
            if ( Info.NextScheduleDate == BatchDateFilter )
            {
               continue;
            }
         }
      }
      NewBatList[Info.Idx] = Info;
   }
}

void __fastcall TBatListForm::ButtonFilterClick(TObject *Sender)
{
   AssignRows();
}
//---------------------------------------------------------------------------

void __fastcall TBatListForm::UpdateButtons(int Row)
{
   UTF8String IdxStr = StringGrid1->Rows[Row]->Strings[0];

   if ( IdxStr == "" )
   {
      ButtonProperty->Enabled = false;
      ButtonGotoThisGroup->Enabled = false;
      return;
   }

   ButtonProperty->Enabled = true;
   ButtonGotoThisGroup->Enabled = StringGrid1->Rows[Row]->Strings[3] != "UNKNOWN";
   return;
}

void __fastcall TBatListForm::StringGrid1SelectCell(TObject *Sender, int ACol,
      int ARow, bool &CanSelect)
{
   UpdateButtons(ARow);
}
//---------------------------------------------------------------------------

void __fastcall TBatListForm::ButtonPropertyClick(TObject *Sender)
{
   MainForm->Portal->SetCurrentBatch(
      StringGrid1->Rows[StringGrid1->Selection.Top]->Strings[0].ToIntDef(1) - 1);
   MainForm->Portal->ShowBatchProperties();
}
//---------------------------------------------------------------------------

void __fastcall TBatListForm::ButtonGotoThisGroupClick(TObject *Sender)
{
   MainForm->Portal->SetCurrentBatch(
      StringGrid1->Rows[StringGrid1->Selection.Top]->Strings[0].ToIntDef(1) - 1);
   MainForm->EnterBatch("");
   Close();
}
//---------------------------------------------------------------------------

void __fastcall TBatListForm::ButtonRefreshClick(TObject *Sender)
{
   MainForm->Refresh();
}
//---------------------------------------------------------------------------

void __fastcall TBatListForm::ButtonSaveClick(TObject *Sender)
{
   SaveDialog1->DefaultExt = "csv";
   SaveDialog1->Filter =
      "Comma-Separated Values (*.csv)|*.csv|All files (*.*)|*.*";
   SaveDialog1->FilterIndex = 1;

   if ( SaveDialog1->InitialDir == "" )
   {
      SaveDialog1->InitialDir = h_g::BaseDir + "bats";
   }

   SaveDialog1->Options = TOpenOptions() << ofOverwritePrompt
      << ofEnableSizing;
   SaveDialog1->Title = UTF8String(h_g::I18nString("t_downloadform:SAVE_FILE_AS"));

   if( !SaveDialog1->Execute() )
   {
      return;
   }

   FILE *f = _wfopen(SaveDialog1->FileName.c_str(), L"wt");

   if ( f == NULL )
   {
      UTF8String TmpStr;
      h_g::ShowMessage(TmpStr.sprintf("Can not create %s", SaveDialog1->FileName.c_str()));
   }

   for ( int i = 0; i < StringGrid1->RowCount; i++ )
   {
      vector<UTF8String> StrVec;

      for ( int j = 0; j < 9; j++ )
      {
         StrVec.push_back(StringGrid1->Rows[i]->Strings[j]);
      }

      fprintf(f, "%s,%s,%s,%s,%s,%s,%s,%s,%s\n",
         StrVec[0].c_str(), StrVec[1].c_str(),
         StrVec[3].c_str(), StrVec[4].c_str(), StrVec[5].c_str(),
         StrVec[6].c_str(), StrVec[7].c_str(), StrVec[8].c_str(),
         StrVec[2].c_str());
   }

   fclose(f);
}
//---------------------------------------------------------------------------

